// src/utils/request.js
import { extend } from 'umi-request';
import { getSessionStorageInfo, getLocalStorageInfo } from './localStorageInfo';
// 接口环境地址
let gatewayUrl = process.env.baseUrl;

const bsinRequest = extend({
  // 配置选项
  errorHandler: (error) => {
    // 错误处理
    const { response } = error;
    if (response && response.status) {
      // 根据不同的响应状态码处理错误
      const errorText = `请求错误 ${response.status}: ${response.statusText}`;
      console.error(errorText);
    } else if (!response) {
      console.error('网络异常，无法连接服务器');
    }
    return response;
  },
});


// 请求拦截
bsinRequest.interceptors.request.use((url, config) => {
  // 请求方法统一为 POST
  config.method = 'POST';
  console.log(gatewayUrl)
  // 获取userInfo和token
  // let userInfo = getLocalStorageInfo('userInfo');
  // let token = getSessionStorageInfo('token')?.token;

  let token =
    'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYmYiOjE2NzIzNjUxOTYsInRlbmFudElkIjoiNjM0NTgyNDQxMzc2NDE1NzQ0MCIsImV4cCI6MTczMjM2NTE5NiwiaWF0IjoxNjcyMzY1MTk2LCJ1c2VySWQiOiIxNTM1OTg0MzA0NTI4NjkxMjAwIn0.ctZTKe23Z_8sR-7fn7629KrzTYZHVyrli3NYezjqdtc';
  // 判断token和用户信息是否存在
  // if (
  //   (!token || !userInfo) &&
  //   config.methodName !== 'getIssueApps' &&
  //   config.methodName !== 'login'
  // ) {
  //   history.push('/login');
  // }
  console.log(gatewayUrl)
  // 判断一些
  const headers = {
    'Content-Type': 'application/json',
    Accept: 'application/json',
    Authorization: token || "",
  };

  let pagination;
  if (config?.bizParams?.pageSize) {
    pagination = {
      pageSize: config?.bizParams?.pageSize,
      pageNum: config?.bizParams?.current,
    };
    delete config?.bizParams?.pageSize;
    delete config?.bizParams?.current;
  }
  // 组装报文
  let data = {}
  if (config?.version) {
    headers.version = config?.version;
  }

  if (pagination) {
    data = {
      ...config.bizParams,
      pagination,
    };
  } else {
    data = {
      ...config.bizParams
    };
  }
  config.headers = {
    ...headers,
  };

  console.log("config")
  console.log(config)
  const requestUrl = gatewayUrl + config.url;

  return {
    url: requestUrl,
    options: { data, ...config },
  };
});

// response拦截器, 处理response
bsinRequest.interceptors.response.use(
  (response, options) => {
    if (response.status === 200) {
      return response
        .clone()
        .json()
        .then((body) => {
          if (body?.code !== '000000') {
            notification.error({
              message: '',
              description: body?.message,
            });
            body = false;
          }
          return body;
        });
    } else {
      notification.error({
        message: '',
        description: codeMessage?.[response.status],
      });
      return false;
    }
  },
  {
    global: false,
  },
);

export default bsinRequest;
